package platformio

import (
	"encoding/json"
	"os"
	"path/filepath"
)

type Platform struct {
	Name        string             `json:"name"`
	Title       string             `json:"title"`
	Description string             `json:"description"`
	Homepage    string             `json:"homepage"`
	License     string             `json:"license"`
	Keywords    []string           `json:"keywords"`
	Engines     Engines            `json:"engines"`
	Repository  Repository         `json:"repository"`
	Version     string             `json:"version"`
	Frameworks  Frameworks         `json:"frameworks"`
	Packages    map[string]Package `json:"packages"`
}

type Engines struct {
	Platformio string `json:"platformio"`
}

type Frameworks struct {
	Arduino         Arduino      `json:"arduino"`
	Esp8266RTOSSDK  Esp8266OSSDK `json:"esp8266-rtos-sdk"`
	Esp8266NonosSDK Esp8266OSSDK `json:"esp8266-nonos-sdk"`
}

type Arduino struct {
	Package string `json:"package"`
	Script  string `json:"script"`
}

type Esp8266OSSDK struct {
	Package     string `json:"package"`
	Script      string `json:"script"`
	Description string `json:"description"`
	Homepage    string `json:"homepage"`
	Title       string `json:"title"`
}

type Package struct {
	Type             string   `json:"type"`
	Optional         *bool    `json:"optional,omitempty"`
	Owner            string   `json:"owner"`
	Version          string   `json:"version"`
	OptionalVersions []string `json:"optionalVersions,omitempty"`
}

type Repository struct {
	Type string `json:"type"`
	URL  string `json:"url"`
}

func LoadPlatformFromFile(filename string) (platform Platform) {
	b, err := os.ReadFile(filename)
	if err != nil {
		return
	}

	err = json.Unmarshal(b, &platform)
	if err != nil {
		return
	}

	return
}

func LoadPlatformFromDir(filedir string) (platform Platform) {
	path := filepath.Join(filedir, "platform.json")
	return LoadPlatformFromFile(path)
}
